package main

import (
	"gin-gorm-project/conf"
	"gin-gorm-project/flags"
	"gin-gorm-project/modules"
	"gin-gorm-project/modules/documents"
	"gin-gorm-project/modules/user"
	"gin-gorm-project/routers"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
)

func main() {
	// 解析参数
	flags.InitFlag()

	// 读取配置文件
	confFile := flags.ConfName()
	c, err := conf.FromYamlFileLoadConfigs(confFile)
	if err != nil {
		log.Panicln("from yaml read errors", err)
	}
	log.Println("read conf:", c)
	log.Println("web server version:", flags.VERSION)
	log.Println("the running PID is", os.Getpid())

	// 初始化gin
	r := gin.Default()
	r.Use(cors())

	// 初始化数据库
	modules.InitDb(c.Db)

	// 使用gorm创建表结构
	if err := documents.InitTable(); err != nil {
		log.Panicln(err)
	}
	if err := user.InitTable(); err != nil {
		log.Println(err)
	}

	// 定义gin路由
	routers.BlogRouters(r)
	routers.UserRouters(r)

	// 启动程序
	log.Fatal(r.Run(c.BlogServer.Bind))
	//r.Run(":9000")
}

func cors() gin.HandlerFunc {
	return func(context *gin.Context) {
		method := context.Request.Method

		context.Header("Access-Control-Allow-Origin", "*")
		context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token, x-token")
		context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH, PUT")
		context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		context.Header("Access-Control-Allow-Credentials", "true")

		if method == "OPTIONS" {
			context.AbortWithStatus(http.StatusNoContent)
		}
	}
}
